<?php
// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit(json_encode(['success' => false, 'msg' => '仅支持POST请求']));
}

// 检查登录状态
session_start();
if (!isset($_SESSION['is_admin'])) {
    exit(json_encode(['success' => false, 'msg' => '未登录']));
}

// 配置
$uploadDir = '../uploads/'; // 确保该目录存在且可写
$maxSize = 5 * 1024 * 1024; // 5MB
$allowedTypes = [
    'image/jpeg', 'image/png', 'image/gif',
    'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'video/mp4', 'video/webm'
];

// 创建上传目录
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// 处理上传
if (!isset($_FILES['file'])) {
    exit(json_encode(['success' => false, 'msg' => '未选择文件']));
}

$file = $_FILES['file'];

// 检查错误
if ($file['error'] !== UPLOAD_ERR_OK) {
    exit(json_encode(['success' => false, 'msg' => '上传错误：' . $file['error']]));
}

// 检查类型
if (!in_array($file['type'], $allowedTypes)) {
    exit(json_encode(['success' => false, 'msg' => '不支持的文件类型']));
}

// 检查大小
if ($file['size'] > $maxSize) {
    exit(json_encode(['success' => false, 'msg' => '文件过大，最大支持5MB']));
}

// 生成文件名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $ext;
$targetPath = $uploadDir . $filename;

// 移动文件
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    // 返回可访问的URL
    $url = str_replace('../', '', $targetPath); // 根据实际部署调整
    exit(json_encode(['success' => true, 'url' => $url]));
} else {
    exit(json_encode(['success' => false, 'msg' => '文件保存失败']));
}